package cn.itsource.smartcampus.interceptor;

import cn.itsource.smartcampus.util.TokenMap;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("进入到了拦截器中");
        String token = request.getHeader("access-token");
        // 1.获取前端从请求头中传递过来的token

        // 2.根据token从map中获取用户登录标识，如果为空说明这个用户没有登录
        Object o = TokenMap.get(token);
        if ("".equals(o) || null == o){
            // 1.告诉前端我响应的是一个JSON
            response.setContentType("application/json;charset=UTF-8");
            // 2.设置响应数据
            PrintWriter writer = response.getWriter();
            writer.write("{\"code\": \"401\", \"success\": false, \"msg\": \"请登录！\"}");

            return false; // 拦截
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
